module one {
	export class MusicCtr {
		private bgName: string;
		private bgChannel: egret.SoundChannel;
		private position: number = 0;

		private startTime: number;
		private playTimes: number;
		private isLoop: boolean;


		private _volume: number = 1;
		public get volume(): number {
			return this._volume;
		}
		public set volume(v: number) {
			this._volume = v;

			if (this.bgChannel) {
				this.bgChannel.volume = v;
			}

		}

		public constructor() {
		}

		public playLastMusic(): void {
			this.play(this.bgName, this.startTime, this.playTimes, this.duration);
		}

		private playCnt:number = 0;
		public play(name: string, startTime: number, playTimes: number, duration: number): void {
			this.duration = duration;
			name = getSoundKey(name);
			if (name == null) {
				return;
			}
			if (this.bgName == name && this.bgChannel) {
				let position = this.bgChannel.position;
				this.next(position);
				return;
			}
			this.playCnt++;
			this.bgName = name;
			this.startTime = startTime;
			this.playTimes = playTimes;
			this.isLoop = playTimes <= 0;

			if (!this.isClosed) {
				this.next(this.startTime);
			}
		}

		private duration:number = 0;
		private interID:number = -1;
		private next(position: number): void {
			if (this.bgChannel) {
				this.bgChannel.stop();
				one.clearInterval(this.interID);
				this.bgChannel = null;
			}
			if (this.isLoop || this.playTimes > 0) {
				let self = this;
				let sound = RES.getRes(this.bgName)
				if (sound == null) {
					let key = this.playCnt;
					RES.getResAsync(this.bgName, () => {
						if (this.playCnt == key) {
							this.next(position);
						}
					}, this);
					return;
				}

				let channel: egret.SoundChannel = this.bgChannel = sound.play(position, 1);
				channel.volume = this._volume;

				let f = ()=> {
					one.clearInterval(this.interID);
					this.playTimes--;
					this.next(this.startTime);
				}

				channel.once(egret.Event.SOUND_COMPLETE, f, channel);
				if (this.duration > 0) {
					this.interID = one.setInterval(()=> {
						let du = this.bgChannel.position;
						if (du >= this.duration) {
							channel.removeEventListener(egret.Event.SOUND_COMPLETE, f, channel);

							f();
						}
					}, 30);
				}
			}
		}

		private isClosed: boolean = false;
		public close(): void {
			if (this.isClosed) {
				return;
			}
			this.isClosed = true;
			one.clearInterval(this.interID);
			if (this.bgChannel) {
				this.position = this.bgChannel.position;
				this.bgChannel.stop();
				this.bgChannel = null;
			}
		}

		public open(): void {
			if (!this.isClosed) {
				return;
			}
			this.isClosed = false;
			this.next(this.position);

			this.position = 0;
		}

		public stopAll():void {
			one.clearInterval(this.interID);
			if (this.bgChannel) {
				this.position = this.bgChannel.position;
				this.bgChannel.stop();
				this.bgChannel = null;
			}
		}
	}
}